import { makeAutoObservable } from 'mobx';
import { FormInstance } from 'antd';
import { ReactNode } from 'react';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';

import { COMMON_PAGINATION } from '@/utils/config';
import request from '@/utils/request';
import { formatParams, getFormValues } from '@/utils/util';
import notification from '@/utils/notification';
import { generateCommonDeleteModal } from '@/utils/renderer';

/** 查询配置 */
export type AxiosConfigType = {
  /** url */
  url?: string;
  /** method */
  method?: string;
};

/** 列配置操作栏设置 */
export type ColumnsConfigBarType = {
  /** 已勾选列 */
  checkedList?: CheckboxValueType[];
  /**
   * 部分选择标识
   * @default false
   */
  indeterminate?: boolean;
  /**
   * 全选标识
   * @default true
   */
  checkAll?: boolean;
};

/** 初始化作用域时参数配置 */
export type StoreInitConfig = {
  /** 查询url */
  queryUrl?: string;

  /** 查询请求方式 */
  queryMethod?: string;

  /**
   * 查询条件处理
   * @example 用于处理请求前的时间参数
   */
  queryFormat?: any;

  /** 新增保存url */
  addUrl?: string;

  /** 新增保存请求方式 */
  addMethod?: string;

  /** 编辑保存url */
  updateUrl?: string;

  /** 编辑保存请求方式 */
  updateMethod?: string;

  /** 删除url */
  deleteUrl?: string;

  /** 删除请求方式 */
  deleteMethod?: string;

  /** 表格是否分页 */
  paging?: boolean;

  /** 表格勾选方式 */
  selectionType?: boolean | 'checkbox' | 'radio';

  /** 表格列 */
  columns?: any[];

  /** 查询表单实例 */
  queryForm?: FormInstance;

  /** 编辑表单实例 */
  editForm?: FormInstance;

  /** 删除前提示 */
  deleteTip?: ReactNode;
};

export default class RbProTableStore {
  private queryConfig: AxiosConfigType = {};

  private queryFormat?: any;

  private addConfig: AxiosConfigType = {};

  private updateConfig: AxiosConfigType = {};

  private deleteConfig: AxiosConfigType = {};

  private paging: boolean | undefined;

  private selectionType: boolean | 'checkbox' | 'radio' | undefined;

  private queryForm: FormInstance | undefined;

  private editForm: FormInstance | undefined;

  private deleteTip: ReactNode | undefined;

  private initColumns: any[] = [];

  private setQueryConfig(config: AxiosConfigType = {}) {
    this.queryConfig = { ...config };
  }

  private setQueryFormat(queryFormat?: any) {
    this.queryFormat = queryFormat;
  }

  private setAddConfig(config: AxiosConfigType = {}) {
    this.addConfig = { ...config };
  }

  private setUpdateConfig(config: AxiosConfigType = {}) {
    this.updateConfig = { ...config };
  }

  private setDeleteConfig(config: AxiosConfigType = {}) {
    this.deleteConfig = { ...config };
  }

  private setPaging(paging = true) {
    this.paging = paging;
  }

  private setSelectionType(selectionType: boolean | 'checkbox' | 'radio' = false) {
    this.selectionType = selectionType;
  }

  private setQueryForm(queryForm: FormInstance<any> | undefined) {
    this.queryForm = queryForm;
  }

  private setEditForm(editForm: FormInstance<any> | undefined) {
    this.editForm = editForm;
  }

  private setDeleteTip(deleteTip: ReactNode | undefined) {
    this.deleteTip = deleteTip;
  }

  private setInitColumns(initColumns: any[] = []) {
    this.initColumns = initColumns;
  }

  constructor() {
    makeAutoObservable(this);
  }

  /** 初始化作用域
   * @param { StoreInitConfig } config
   */
  initStore(config: StoreInitConfig = {}) {
    this.setQueryConfig({ url: config.queryUrl, method: config.queryMethod });
    this.setQueryFormat(config.queryFormat);
    this.setAddConfig({ url: config.addUrl, method: config.addMethod });
    this.setUpdateConfig({ url: config.updateUrl, method: config.updateMethod });
    this.setDeleteConfig({ url: config.deleteUrl, method: config.deleteMethod });
    this.setPaging(config.paging);
    this.setSelectionType(config.selectionType);
    this.setColumns(config.columns);
    this.setInitColumns(config.columns);
    this.setColumnsConfigBar({
      checkedList: config.columns?.map((c: any) => c.dataIndex) || [],
      indeterminate: false,
      checkAll: true
    });
    this.setQueryForm(config.queryForm);
    this.setEditForm(config.editForm);
    this.setDeleteTip(config.deleteTip);
  }

  /** 表格数据 */
  tableData: any[] = [];

  /** 设置 表格数据 */
  setTableData(newTableData: any[]) {
    this.tableData = [...newTableData];
  }

  /** 已勾选行集合 */
  selected: any[] = [];

  /** 设置 已勾选行集合 */
  setSelected(newSelected: any[]) {
    this.selected = [...newSelected];
  }

  /** 已勾选行key集合 */
  selectedKeys: any[] = [];

  /** 设置 已勾选行key集合 */
  setSelectedKeys(newSelectedKeys: any[]) {
    this.selectedKeys = [...newSelectedKeys];
  }

  /** 表格实际的columns */
  columns: any[] = [];

  /** 设置 表格实际的columns */
  setColumns(newColumns: any[] = []) {
    this.columns = [...newColumns];
  }

  /** 表格的分页 */
  pagination: any = { ...COMMON_PAGINATION };

  /** 设置 表格的分页 */
  setPagination(newPagination: any) {
    this.pagination = { ...COMMON_PAGINATION, ...newPagination };
  }

  /**
   * 表格按钮操作类型
   * @example 'create' | 'update'
   */
  operationType = '';

  /**
   * 设置 表格按钮操作类型
   * @example 'create' | 'update'
   */
  setOperationType(newOperationType: string) {
    this.operationType = newOperationType;
  }

  /** 列配置操作栏设置 */
  columnsConfigBar: ColumnsConfigBarType = {};

  /** 设置 列配置操作栏设置 */
  setColumnsConfigBar(newColumnsConfigBar: ColumnsConfigBarType) {
    this.columnsConfigBar = { ...newColumnsConfigBar };
  }

  /** 新增｜编辑表单抽屉是否打开 */
  openFlag = false;

  /** 设置 新增｜编辑表单抽屉显隐 */
  setOpenFlag(newOpenFlag: boolean) {
    this.openFlag = newOpenFlag;
  }

  /** 整个页面加载状态 */
  loading = false;

  /** 设置 整个页面加载状态 */
  setLoading(newLoading: boolean) {
    this.loading = newLoading;
  }

  /** 保存时抽屉加载状态 */
  saveLoading = false;

  /** 设置 保存时抽屉加载状态 */
  setSaveLoading(newSaveLoading: boolean) {
    this.saveLoading = newSaveLoading;
  }

  /** 页面列表数据查询接口 */
  async query(params?: any) {
    if (!this.queryConfig.url) return;
    this.setLoading(true);

    const formParams = this.queryForm && (await getFormValues(this.queryForm));
    request({
      ...this.queryConfig,
      params: formatParams(
        { ...(this.paging ? COMMON_PAGINATION : null), ...formParams, ...params },
        this.queryFormat
      )
    })
      .then((res: any) => {
        if (res) {
          const { current, size, total, records = [] } = res;
          // 设置分页数据
          if (this.paging) this.setPagination({ current, size: size, total });
          this.setTableData(records);
          // 查询重置勾选
          if (this.selectionType) {
            this.setSelectedKeys([]);
            this.setSelected([]);
          }
        }
      })
      .finally(() => {
        this.setLoading(false);
      });
  }

  /** 分页切换重新查询表格数据 */
  async handleTableChange(
    { current, size }: any,
    _: any,
    { field: sortField, order: sortOrder }: any
  ) {
    if (this.queryForm) {
      const fields = await getFormValues(this.queryForm);
      console.log(sortOrder);

      await this.query(
        Object.assign(
          { ...fields, current, size },
          {
            column: sortOrder ? sortField : null,
            asc: sortOrder ? (sortOrder === 'ascend' ? true : false) : null
          }
        )
      );
    }
  }

  /** 新建、编辑保存 */
  async handleSave() {
    if (!this.editForm) return;

    // 表单未修改
    if (!this.editForm.isFieldsTouched()) {
      // 关闭抽屉
      this.setOpenFlag(false);
      return;
    }

    // 校验获取值
    const fields = await this.editForm.validateFields();

    // 校验通过
    if (fields) {
      this.setSaveLoading(true);
      const config = this.operationType === 'update' ? this.updateConfig : this.addConfig;
      request({
        ...config,
        data: { ...this.selected[0], ...fields }
      })
        .then(async (res: any) => {
          if (res) {
            notification.success();
            // 关闭抽屉
            this.setOpenFlag(false);
            const { current, size }: any = this.paging ? this.pagination : {};
            // 查询最新数据
            await this.query({ current, size });
          }
        })
        .finally(() => {
          this.setSaveLoading(false);
        });
    }
  }

  /** 勾选删除 */
  handleDelete() {
    if (!this.selectedKeys.length) return;

    const that = this;
    generateCommonDeleteModal({
      title: that.deleteTip,
      onOk() {
        that.setLoading(true);
        request({
          ...that.deleteConfig,
          data: that.selectedKeys
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              // 查询最新数据
              that.query();
            }
          })
          .finally(() => {
            that.setLoading(false);
          });
      }
    });
  }

  /** 列配置操作栏设置变化 */
  handleColumnsChange(checkedValues: CheckboxValueType[]) {
    this.setColumnsConfigBar({
      checkedList: checkedValues,
      indeterminate: !!checkedValues.length && checkedValues.length < this.initColumns.length,
      checkAll: checkedValues.length === this.initColumns.length
    });
    this.setColumns(this.initColumns.filter((c: any) => checkedValues.includes(c.dataIndex)));
  }

  /** 列配置操作栏设置全选变化 */
  handleColumnsCheckAllChange(e: any) {
    this.setColumnsConfigBar({
      checkedList: e.target.checked ? this.initColumns.map((c: any) => c.dataIndex) : [],
      indeterminate: false,
      checkAll: e.target.checked
    });
    this.setColumns(e.target.checked ? this.initColumns : []);
  }

  /** 列配置操作栏设置重置 */
  handleColumnsReset() {
    this.setColumnsConfigBar({
      checkedList: this.initColumns.map((c: any) => c.dataIndex),
      indeterminate: false,
      checkAll: true
    });
    this.setColumns(this.initColumns);
  }
}
